#include"include.h"

bitfield_t *bitfieldInit(unsigned int len)
{
   bitfield_t *b = malloc(sizeof(bitfield_t));
   b->length = len;
   b->bitfield = malloc(len);
   memset(b->bitfield, 0, len);
   return b;
}

short bitfieldGet(bitfield_t *b, unsigned int i)
{
   if(i >= b->length)
   {
      loggerLog(LOG_WARN, "Tried to access out of bound index on bitfield get. %d >= %d.\n", i, b->length);
      return -1;
   }
   return ((b->bitfield[i/8] & (1 << (i%8))) != 0);
}

void bitfieldSet(bitfield_t *b, unsigned int i, short val)
{
   if(i >= b->length)
   {
      loggerLog(LOG_WARN, "Tried to access out of bound index on bitfield set. %d >= %d.\n", i, b->length);
      return;
   }
   if(val)
      b->bitfield[i/8] |= ((1 << (i%8)));
   else
      b->bitfield[i/8] &= ~(1 << (i%8));
}

int bitfieldFull(bitfield_t *b)
{
   int i;
   for(i=0;i<b->length;i++)
      if(bitfieldGet(b, i) == 0)
         return 0;
   return 1;
}

double bitfieldPercent(bitfield_t *b)
{
   int i;
   int count=0;
   for(i=0;i<b->length;i++)
   {
      count += bitfieldGet(b, i);
   }
   return (double)count / (double)b->length;
}
void bitfieldPrint(bitfield_t *b)
{
   int i;
   for(i=0;i<b->length;i++)
   {
      printf("%d", ((b->bitfield[i/8] & (1 << i%8)) != 0));
   }
   printf("\n");
}

unsigned int bitfieldGetLen(bitfield_t *b)
{
   return b->length;
}

int bitfieldSubFull(bitfield_t *b, unsigned int len)
{
   int i;
   for(i=0;i<len;i++)
      if(bitfieldGet(b, i) == 0)
         return 0;
   return 1;
}
